package commands

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"strconv"
	"time"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var OeAdSyncLogger *logrus.Logger

// InitOeAdSyncLogger 移除 init() 函数，改为显式初始化函数
func InitOeAdSyncLogger() {
	// 确保在 common 初始化后调用
	OeAdSyncLogger = core.InitLogger(common.LogsErrorMap[23])
}

func CopyOeadAccount() {
	// 获取 handle_status = 1 AND type = 1 的所有 parent 值
	var parent []string
	err := common.DB.Model(&models.CopyAccountList{}).Where("handle_status = 1 AND type = 3 AND account_id <> 0").
		Group("parent").Pluck("parent", &parent).Error
	if err != nil {
		OeAdSyncLogger.Error("查询 parent 数据出错: ", err)
		fmt.Println("查询 parent 数据出错: ", err)
		return
	}

	if len(parent) == 0 {
		OeAdSyncLogger.Info("没有需要处理的数据")
		fmt.Println("没有需要处理的数据")
		return
	}

	// 查询所有 copy 数据
	var copyS []models.CopyAccountList
	err = common.DB.
		Where("handle_status = 1 AND type = 3 AND account_id <> 0").
		Find(&copyS).Error
	if err != nil {
		OeAdSyncLogger.Error("查询 copy 数据失败: ", err)
		fmt.Println("查询 copy 数据失败: ", err)
		return
	}

	// 更新 handle_status 为 2
	err = common.DB.Model(&models.CopyAccountList{}).
		Where("handle_status = 1 AND type = 3 AND account_id <> 0").
		Update("handle_status", 2).Error
	if err != nil {
		OeAdSyncLogger.Error("更新数据出错: ", err)
		fmt.Println("更新数据出错: ", err)
		return
	}

	// 查询 parent 对应的账户信息
	var oeAdData []models.ImportOead
	err = common.DBDk.Where("account_id IN (?)", parent).Find(&oeAdData).Error
	if err != nil {
		OeAdSyncLogger.Error("查询视图数据出错: ", err)
		fmt.Println("查询视图数据出错: ", err)
		return
	}

	// 将 tencentData 转换为 map，以 account_id 为键
	parentMap := make(map[string]models.ImportOead)
	for _, item := range oeAdData {
		parentMap[item.AccountID] = item
	}

	// 遍历 copyS 处理每条记录
	for _, item := range copyS {
		parent := strconv.Itoa(item.Parent)

		// 检查 parent 是否存在
		parentInfo, exists := parentMap[parent]
		if !exists {
			msg := fmt.Sprintf("%s 不存在广告主表，跳过", parent)
			OeAdSyncLogger.Info(msg)
			fmt.Println(msg)
			continue
		}

		// 构造表名
		tableName := "import_oead"

		// 构造插入数据
		insertData := map[string]interface{}{
			"account_id":         item.AccountID,
			"open_medium_name":   getValueOrDefault(item.Username, "小助手"),
			"update_medium_name": getValueOrDefault(item.Username, "小助手"),
			"remark":             "小助手复制户" + getValueOrDefault(item.Username, ""),
			"created_at":         time.Now().Format("2006-01-02 15:04:05"),
			"year":               time.Now().Format("2006") + "年",
			"is_robot":           2,
			"month":              time.Now().Format("01") + "月",
			"day":                time.Now().Format("01") + "月" + time.Now().Format("02") + "日",
			"date":               time.Now().Format("2006-01-02") + " 00:00:00",
			"medium":             getValueOrDefault(item.Username, "小助手"),
			"account_name":       item.AccountName,
		}

		// 添加 parentInfo 中的其他字段（除了 id）
		OeAdStructToMap(parentInfo, insertData)

		// 获取表字段列表 - 使用 SHOW COLUMNS FROM 语句
		columns, err := getTableColumns(tableName)
		if err != nil {
			OeAdSyncLogger.Error(fmt.Sprintf("获取表 %s 字段失败: %v", tableName, err))
			fmt.Printf("获取表 %s 字段失败: %v\n", tableName, err)
			continue
		}

		// 过滤数据，只保留允许的字段
		filteredData := filterDataByColumns(insertData, columns)

		// 记录日志
		OeAdSyncLogger.Info(fmt.Sprintf("记录数据: columns=%v, data=%v, copy=%+v", columns, filteredData, item))

		// 插入数据
		err = insertIntoTable(tableName, filteredData)
		if err != nil {
			msg := fmt.Sprintf("%s 新增插入失败，跳过", parent)
			OeAdSyncLogger.Info(msg)
			fmt.Println(msg)
			continue
		}
	}
}

// OeAdStructToMap 将结构体字段添加到 map 中（除了 id 字段）
func OeAdStructToMap(info models.ImportOead, data map[string]interface{}) {
	// 注意：这里需要根据实际的 TencentAccountView 结构体字段进行调整
	data["platform"] = info.Platform
	data["open_id"] = info.OpenID
	data["examine_status"] = info.ExamineStatus
	data["business_license"] = info.BusinessLicense
	data["industry_2024"] = info.Industry2024
	data["second_industry_2024"] = info.SecondIndustry2024
	data["industry"] = info.Industry
	data["second_industry"] = info.SecondIndustry
	data["bidding_type_2022"] = info.BiddingType2022
	data["bidding_type_2023"] = info.BiddingType2023
	data["bidding_type_2024"] = info.BiddingType2024
	data["date_type_old"] = info.DateTypeOld
	data["date_type"] = info.DateType
	data["sale"] = info.Sale
	data["first_business"] = info.FirstBusiness
	data["second_business"] = info.SecondBusiness
	data["channel"] = info.Channel
	data["company"] = info.Company
	data["link"] = info.Link
	data["set_product"] = info.SetProduct
	data["optimization"] = info.Optimization
	data["log_id"] = info.LogID
	data["import"] = info.Import
	data["uid"] = info.UID
	data["group_name"] = info.GroupName
	data["sku"] = info.Sku
	data["is_old"] = info.IsOld
	data["name_core"] = info.NameCore
	data["old_sale"] = info.OldSale
	data["is_transfer"] = info.IsTransfer
	data["old_company"] = info.OldCompany
	data["old_first_business"] = info.OldFirstBusiness
	data["old_second_business"] = info.OldSecondBusiness
	data["update_account_status_at"] = info.UpdateAccountStatusAt
	data["is_brand_client"] = info.IsBrandClient
	data["first_business_2025_5"] = info.FirstBusiness202505
	data["second_business_2025_5"] = info.SecondBusiness202505
}
